package com.bwf.lgqingdan.gui.activity;

import android.annotation.TargetApi;
import android.content.Intent;
import android.graphics.Rect;
import android.graphics.drawable.ColorDrawable;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bwf.lgqingdan.QingdanApplication;
import com.bwf.lgqingdan.R;
import com.bwf.lgqingdan.entity.ArticlesBean;
import com.bwf.lgqingdan.entity.ResponseCategoryThing;
import com.bwf.lgqingdan.entity.ThingsBean;
import com.bwf.lgqingdan.gui.adapter.CategoryThingMainAdapter;
import com.bwf.lgqingdan.gui.adapter.PopSortListAdapter;
import com.bwf.lgqingdan.gui.adapter.base.BaseRecycleViewAdapter;
import com.bwf.lgqingdan.mvp.presenter.CategoryThingPresenter;
import com.bwf.lgqingdan.mvp.presenter.impl.CategoryThingPresenterImpl;
import com.bwf.lgqingdan.mvp.view.CategoryThingView;
import com.bwf.lgqingdan.utils.IntentUtils;
import com.cjj.MaterialRefreshLayout;
import com.cjj.MaterialRefreshListener;
import com.facebook.drawee.view.SimpleDraweeView;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by Administrator on 2016/11/14.
 * 分类对应的商品 界面
 */
public class CategoryThingActivity extends ActivityBase implements CategoryThingView, BaseRecycleViewAdapter.OnItemClickListener<ThingsBean> {
    @BindView(R.id.back)
    ImageView back;
    @BindView(R.id.ll_title_mid)
    LinearLayout llTitleMid;
    @BindView(R.id.recycleView)
    RecyclerView recycleView;
    @BindView(R.id.refreshLayout)
    MaterialRefreshLayout refreshLayout;
    @BindView(R.id.root)
    View root;
    @BindView(R.id.title)
    TextView title;
    @BindView(R.id.img_arrow)
    ImageView imgArrow;
    @BindView(R.id.layout_title)
    RelativeLayout layoutTitle;
    @BindView(R.id.view_cover)
    View viewCover;
    private CategoryThingPresenter presenter;
    public static final String TAG_CATEGORY_ID = "categoryId";
    public static final String TAG_CATEGORY_NAME = "categoryName";
    private int categoryId;
    private String categoryName;
    private int articlesCount;
    private int thingsCount;
    private String imgUrl;
    private String excerpt;
    private CategoryThingMainAdapter categoryThingMainAdapter;
    private GridLayoutManager layoutManager;

    @Override
    public int getContentViewResID() {
        return R.layout.activity_category_thing;
    }

    @Override
    protected void initViews() {
        initIntentData();
        ButterKnife.bind(this);
        root.setPadding(0, getStatusHeight(), 0, 0);
        title.setText(categoryName);
        layoutManager = new GridLayoutManager(this, 2);
        layoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
            @Override
            public int getSpanSize(int position) {
                if (position < categoryThingMainAdapter.getHeaderItemCount()) {
                    return 2;
                }
                return 1;
            }
        });
        recycleView.setLayoutManager(layoutManager);
        //设置item的间距
        int spacingInPixels = getResources().getDimensionPixelSize(R.dimen.item_space);
        recycleView.addItemDecoration(new SpaceItemDecoration(spacingInPixels));
        categoryThingMainAdapter = new CategoryThingMainAdapter(this, this);
        recycleView.setAdapter(categoryThingMainAdapter);
        categoryThingMainAdapter.setOnItemClickListener(this);
        refreshLayout.setLoadMore(true);
        refreshLayout.setMaterialRefreshListener(refreshListener);
//        recycleView.addOnScrollListener(recycleViewScrollListener);
    }

    /**
     * 下拉刷新的监听
     */
    private MaterialRefreshListener refreshListener = new MaterialRefreshListener() {
        @Override
        public void onRefresh(MaterialRefreshLayout materialRefreshLayout) {
            loadInitData();
        }

        @Override
        public void onRefreshLoadMore(MaterialRefreshLayout materialRefreshLayout) {
            super.onRefreshLoadMore(materialRefreshLayout);
            loadNextPageThings();
        }
    };
//    private boolean isNoMoreData;
//    private boolean isLoading;
//    /**
//     * RecycleView的滚动监听
//     * 实现加载更多功能
//     */
//    private RecyclerView.OnScrollListener recycleViewScrollListener = new RecyclerView.OnScrollListener() {
//        @Override
//        public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
//            super.onScrolled(recyclerView, dx, dy);
//            if (isNoMoreData) {
//                return;
//            }
//            int lastVisibleItem = layoutManager.findLastVisibleItemPosition();
//            int totalItemCount = layoutManager.getItemCount();
//            Log.d("MainListFragment", "lastVisibleItem:" + lastVisibleItem + ",totalItemCount:" + totalItemCount + ",dy:" + dy);
//            if (lastVisibleItem == totalItemCount - 1) {
//                if (isLoading) {
//                    Log.d(TAG_DETAIL_FROM_NETWORK, "ignore manually update!");
//                } else {
//                    isLoading = true;
//                    loadNextPageThings();
//                }
//            }
//        }
//    };

    /**
     * 加载下一页商品
     */
    private void loadNextPageThings() {
//        isLoading = true;
        presenter.loadNextPageThings();
    }

    private void initIntentData() {
        Intent intent = getIntent();
        categoryName = intent.getStringExtra(TAG_CATEGORY_NAME);
        categoryId = intent.getIntExtra(TAG_CATEGORY_ID, 0);
    }

    @Override
    protected void initDatas() {
        presenter = new CategoryThingPresenterImpl(categoryId, this);
        new Handler(){
            @Override
            public void handleMessage(Message msg) {
                refreshLayout.autoRefresh();
            }
        }.sendEmptyMessageDelayed(0,350);
    }

    private void loadInitData() {
        presenter.loadInitData();
//        isLoading = true;
//        isNoMoreData = false;
    }

    private ResponseCategoryThing.TagDetailsRelatedTagsBean.BodyBean.RelatedTagsData tagDetailsRelatedTagsData;

    @Override
    public void showTagDetailsRelatedTags(ResponseCategoryThing.TagDetailsRelatedTagsBean.BodyBean.RelatedTagsData tagDetailsRelatedTagsData) {
        this.tagDetailsRelatedTagsData = tagDetailsRelatedTagsData;
        categoryThingMainAdapter.setRelatedTags(tagDetailsRelatedTagsData.getRelatedTags());
        try{
            //可能不存在图片
            imgUrl = tagDetailsRelatedTagsData.getCoverImage().getThumbnail().getImageUrl();
        }catch (Exception e){
            imgUrl = "";
        }
        articlesCount = tagDetailsRelatedTagsData.getArticleCount();
        thingsCount = tagDetailsRelatedTagsData.getThingCount();
        excerpt = tagDetailsRelatedTagsData.getExcerpt();
        refreshLayout.finishRefresh();
    }

    @Override
    public void showTagDetailsArticles(List<ArticlesBean> articles) {
        categoryThingMainAdapter.setArticles(articles);
    }

    @Override
    public void showThings(int page, List<ThingsBean> things) {
        if (page == 1) {
            categoryThingMainAdapter.setDatas(things);
        } else {
            categoryThingMainAdapter.addDatas(things);
            refreshLayout.finishRefreshLoadMore();
        }
//        isLoading = false;
    }


    @Override
    public void clickMoreArticles() {
        IntentUtils.gotoArticleListActivity(this,categoryId);
    }

    @Override
    public void clickItemRelatedTags(ResponseCategoryThing.TagDetailsRelatedTagsBean.BodyBean.RelatedTagsData.RelatedTagsBean data) {
        IntentUtils.gotoCategoryThingActivity(this,data.getId(),data.getName());
    }

    @Override
    public void clickItemArticle(ArticlesBean data) {
        IntentUtils.gotoArticleDetailActivity(this, data.getId());
    }

    @Override
    public void clickThingSort() {//点击了排序
        showSortPop();
    }

    @Override
    public void showLoadInitDataFailed(String failedMsg) {
//        isLoading = false;
        Toast.makeText(this, failedMsg, Toast.LENGTH_SHORT).show();
        refreshLayout.finishRefresh();
    }


    @Override
    public void showNoMoreThings() {
//        isNoMoreData = true;
        Toast.makeText(this, getString(R.string.noMoreData), Toast.LENGTH_SHORT).show();
    }

    @Override
    public void showInitThings(List<ThingsBean> things) {
        if(popSortViewHolder != null) {
            popSortViewHolder.sortListAdapter.refresh();
        }
        showThings(1,things);
    }

    @Override
    public void showLoadNextThingsFaied(String failed) {
//        isLoading = false;
        refreshLayout.finishRefreshLoadMore();
        Toast.makeText(this, failed, Toast.LENGTH_SHORT).show();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @OnClick({R.id.back, R.id.ll_title_mid})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.ll_title_mid:
                if (!imgArrow.isSelected()) {
                    imgArrow.setSelected(true);
                    showExcerptPop();
                } else {
                    imgArrow.setSelected(false);
                }
                break;
            case R.id.back:
                finish();
                break;
        }
    }

    private PopupWindow popupWindowSort;
    private PopSortViewHolder popSortViewHolder;
    /**
     * 显示 排序的PopupWindow
     */
    @TargetApi(Build.VERSION_CODES.KITKAT)
    private void showSortPop() {
        if (popupWindowSort == null) {
            popupWindowSort = new PopupWindow(WindowManager.LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.WRAP_CONTENT);
            View view = LayoutInflater.from(this).inflate(R.layout.layout_pop_sort, null);
            popSortViewHolder = new PopSortViewHolder(view);
            popupWindowSort.setContentView(view);
            popupWindowSort.setOnDismissListener(new PopupWindow.OnDismissListener() {
                @Override
                public void onDismiss() {
                    viewCover.setVisibility(View.GONE);
                }
            });
            popupWindowSort.setFocusable(true);
            /**
             * 如果有背景，则会在contentView外面包一层PopupViewContainer之后作为mPopupView，如果没有背景，则直接用contentView作为mPopupView。
             而这个PopupViewContainer是一个内部私有类，它继承了FrameLayout，在其中重写了Key和Touch事件的分发处理
             */
            popupWindowSort.setBackgroundDrawable(new ColorDrawable(0x00000000));
        }
        viewCover.setVisibility(View.VISIBLE);
        popupWindowSort.showAsDropDown(findViewById(R.id.img_things_sort),0,0, Gravity.RIGHT);//sdk>=19
    }

    private PopupWindow popupWindowExcerpt;
    private PopviewExcerptViewHolder popviewExcerptViewHolder;

    /**
     * 显示PopupWindow
     */
    private void showExcerptPop() {
        if (popupWindowExcerpt == null) {
            popupWindowExcerpt = new PopupWindow(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT);
            View view = LayoutInflater.from(this).inflate(R.layout.subview_category_thing_excerpt_pop, null);
            popviewExcerptViewHolder = new PopviewExcerptViewHolder(view);
            popupWindowExcerpt.setContentView(view);
            popupWindowExcerpt.setOnDismissListener(new PopupWindow.OnDismissListener() {
                @Override
                public void onDismiss() {
                    imgArrow.setSelected(false);
                    viewCover.setVisibility(View.GONE);
                }
            });
            popupWindowExcerpt.setFocusable(true);
            /**
             * 如果有背景，则会在contentView外面包一层PopupViewContainer之后作为mPopupView，如果没有背景，则直接用contentView作为mPopupView。
             而这个PopupViewContainer是一个内部私有类，它继承了FrameLayout，在其中重写了Key和Touch事件的分发处理
             */
            popupWindowExcerpt.setBackgroundDrawable(new ColorDrawable(0x00000000));
        }
        viewCover.setVisibility(View.VISIBLE);
        popupWindowExcerpt.showAsDropDown(layoutTitle);
        setPopupData();//为PopupWindow中的视图控件设置数据
    }

    /**
     * 为PopupWindow中的视图控件设置数据
     */
    private void setPopupData() {
        if (tagDetailsRelatedTagsData == null) {
            return;
        }
        popviewExcerptViewHolder.imagePop.setImageURI(imgUrl);
        popviewExcerptViewHolder.tvArticlesCount.setText(getString(R.string.articles_count, articlesCount));
        popviewExcerptViewHolder.tvThingsCount.setText(getString(R.string.things_count, thingsCount));
        popviewExcerptViewHolder.tvExcerpt.setText(excerpt);
    }

    @Override
    public void onItemClick(int position, View view, ThingsBean data) {
        QingdanApplication.instance.thingsBean = data;
        IntentUtils.gotoThingDetailActivity(this,data.getId(), false);
    }

    class PopviewExcerptViewHolder {
        @BindView(R.id.image_pop)
        SimpleDraweeView imagePop;
        @BindView(R.id.tv_things_count)
        TextView tvThingsCount;
        @BindView(R.id.tv_articles_count)
        TextView tvArticlesCount;
        @BindView(R.id.tv_excerpt)
        TextView tvExcerpt;

        PopviewExcerptViewHolder(View view) {
            ButterKnife.bind(this, view);
        }
    }

    /**
     * 控制RecycleView中Item之间的间距
     */
    public class SpaceItemDecoration extends RecyclerView.ItemDecoration {

        private int space;

        public SpaceItemDecoration(int space) {
            this.space = space;
        }

        @Override
        public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
            int childAdapterPosition = parent.getChildAdapterPosition(view);
            if (childAdapterPosition >= categoryThingMainAdapter.getHeaderItemCount()) {
                if (childAdapterPosition % 2 == 1) {
                    outRect.left = space ;
//                    outRect.right = space;
                } else {
//                    outRect.left = space;
                    outRect.right = space;
                }
                if(childAdapterPosition == categoryThingMainAdapter.getHeaderItemCount() ||
                        childAdapterPosition == categoryThingMainAdapter.getHeaderItemCount()+1){
                    outRect.top = space;
                }
//                outRect.top = space;
//                outRect.bottom = space;
            }
        }
    }

    class PopSortViewHolder implements AdapterView.OnItemClickListener {
        @BindView(R.id.listview_pop_sort)
        ListView listviewPopSort;
        PopSortListAdapter sortListAdapter;
        PopSortViewHolder(View view) {
            ButterKnife.bind(this, view);
            sortListAdapter = new PopSortListAdapter(view.getContext());
            String[] strings = getResources().getStringArray(R.array.things_sort_texts);
            for (String text : strings) {
                sortListAdapter.getDatas().add(text);
            }
            listviewPopSort.setAdapter(sortListAdapter);
            listviewPopSort.setOnItemClickListener(this);
        }
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            if(sortListAdapter.setSelectedPosition(position)){
                switch (position){
                    case 0:
                        presenter.loadNextPageNewesTagDetailsThings();
                        break;
                    case 1:
                        presenter.loadNextPageHottestTagDetailsThings();
                        break;
                    case 2:
                        presenter.loadNextPagePriceAscTagDetailsThings();
                        break;
                    case 3:
                        presenter.loadNextPagePriceDescTagDetailsThings();
                        break;
                }
//                isNoMoreData = false;
            }
            popupWindowSort.dismiss();
        }
    }
}
